﻿using System.Diagnostics.CodeAnalysis;

namespace System;

public static class ByteExtensions
{
    /// <summary>
    /// 将字节数组中的数据转为十六进制字符串返回
    /// </summary>
    /// <remarks>
    /// Convert.ToHexString 和 BitConverter.ToString 方法可以实现相同功能
    /// </remarks>
    /// <param name="bytes">字节数组</param>
    /// <param name="uppercase">是否返回大写的字符串</param>
    /// <returns></returns>
    public static string ToHexString(this IEnumerable<byte> bytes, bool uppercase = false)
    {
        var format = uppercase ? "X2" : "x2";
        var sb = new StringBuilder();
        foreach (var item in bytes)
        {
            sb.Append(item.ToString(format));
        }
        return sb.ToString();
    }

    /// <summary>
    /// 克隆字节数组
    /// </summary>
    /// <param name="src"></param>
    /// <returns></returns>
    [return: NotNullIfNotNull(nameof(src))]
    public static byte[]? CloneByteArray(this byte[]? src)
    {
        if (src == null)
        {
            return null;
        }

        return (byte[])(src.Clone());
    }
}
